//
//  LTMainController.m
//  LocalTravel
//
//  Created by zheng ji on 14-2-27.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTMainController.h"
#import "constants.h"
#import "CommonConfigUtil.h"
#import "LTAppDelegate.h"
#define left_margin 5
#define top_margin 25
#define title_height 20//标题栏高度
#define searchField_height 30  //搜索框高度
#define visitTabelView_height 100 //主题表格高度
#define themeTabelView_height 450 //主题表格高度
#define google_ad_height 60 //广告高度
@interface LTMainController ()
{
    
    LTThemeView* _themeTabelView;
    LTLastVisitView* _visitView;//最近访问

    //UIView* leftPanel;
    //UIView* rightPanel;
    
     NSUserDefaults *myDefaults;
    //AMapSearchAPI* search;
    
    CLLocationManager *_currentLoaction;
    
    LTTitleView* _titleView;

    NSString* _currentCityID;//当前城市ID
    NSString* _currentCityName;//当前城市名称

    LTAppDelegate* _appDelegate;
    
    UICollectionView *_collectionView;
    NSArray* _arrayScenery;//景点
    
    UILabel *_loadMoreTip;//加载更多的提示
    //GADBannerView *bannerView_;
    UIPopoverController* _popoverDetail;
   
    AdvView *advView;
    MobiSageAdBanner * adBanner;


    int _currentPage;//当前页数
    int _totalPage;//总页数
    int _pageSize=30;//每页数量
    NSString* _keyWord;//搜索关键词
    int  _distance;
    double _currentPostionlatitude;
    double _currentPostionlongitude;
    NSString * _themeId;//主题ID

    NSMutableArray*  _lastVisitSceneryArray;//最近访问记录
}
@end

@implementation LTMainController
- (UIViewController *)viewControllerToPresent
{
    return self;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   myDefaults=[NSUserDefaults standardUserDefaults];

    NSString* _currentCityID;//当前城市ID
    NSString* _currentCityName;//当前城市名称

     _currentCityID=[myDefaults objectForKey:@"currentCityID"];
     _currentCityName=[myDefaults objectForKey:@"_currentCityName"];

     if(_currentCityID==nil){
        _currentCityID=@"0";
	_currentCityName=@"全国";

     }

    
    _appDelegate=[[UIApplication sharedApplication] delegate];
    
    _currentLoaction = [[CLLocationManager alloc] init];
    _currentLoaction.delegate = self;
    
    _currentLoaction.distanceFilter = 1000;
    
    _currentLoaction.desiredAccuracy = kCLLocationAccuracyBest;
    [_currentLoaction startUpdatingLocation];
    
   
     

    [self initLeftPanelUI];
    [self initRightPanelUI];
    
    if(![CommonConfigUtil checkNetworkReachable]){
        
      UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"没有可用的网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        alertView=nil;
    }
    [_titleView showActivityIndicator:@"正在定位您所在的城市..."];
   
    
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkVersionTimer:) userInfo:nil repeats:NO];
}

-(void) checkVersionTimer:(NSTimer*)theTimer{
    [self checkVersion];
    [theTimer invalidate];
}



-(void)checkVersion{
    
    if([CommonConfigUtil checkVersion]){
        
        NSString *versionNumber=[myDefaults objectForKey:@"versionNumber"];
        NSString *appUrl=[myDefaults objectForKey:@"appUrl"];
        // NSString *appCommentUrl=[myDefaults objectForKey:@"appCommentUrl"];
        NSString *description=[myDefaults objectForKey:@"description"];
        
        if(nil==appUrl)appUrl=@"";
        if(nil==versionNumber)versionNumber=@"";
        if(nil==description)description=@"";
        
        
        if(![@"" isEqualToString:appUrl] && nil!=versionNumber&& ![@"" isEqualToString:versionNumber]&& [versionNumber compare: [CommonConfigUtil getCurrVersion] ]==NSOrderedDescending ){
            
            
            NSString *strMessge;
            if(nil!=description&&![@"" isEqualToString:description]){
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！%@",versionNumber,description];
            }else{
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！是否需要升级？",versionNumber];
            }
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本升级" message:strMessge                                                           delegate:self  cancelButtonTitle:@"立即升级" otherButtonTitles: @"忽略",nil];
            [alert setTag:1];
            
            [alert show];
            
            alert=nil;
        }
        
    }
    
}




- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if([alertView tag]==1&&buttonIndex == 0) {
        
        NSString *appUrl=  [myDefaults objectForKey:@"appUrl"];
        if(nil!=appUrl && ![@"" isEqualToString:appUrl]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrl]];
        }
        
    }
    
}



- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [_currentLoaction stopUpdatingLocation];
    
    _currentPostionlatitude=newLocation.coordinate.latitude;
    _currentPostionlongitude=newLocation.coordinate.longitude;
     
   // NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
   // NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
   // NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if(placemarks.count>0){
           CLPlacemark* _placeMark = [placemarks objectAtIndex:0];
         //_locationLabel.text = _placeMark.administrativeArea;
           //NSLog(@"%@",_placeMark.locality);

             
              NSString* cityName=_placeMark.locality;
	      if([cityName hasSuffix:@"市"]) {
                 cityName=[cityName substringToIndex:cityName.length -1];
               }
              NSString* cityID=[_appDelegate getCityIDByName:cityName];

             [myDefaults setObject:cityName forKey:@"currentCityName" ];
	     [myDefaults setObject:cityID.locality forKey:@"currentCityID" ];

             [myDefaults synchronize];

           // [_titleView setCurrentCity:_placeMark.locality];
            //[self searchSceneryByCityName:_placeMark.locality];

            
        }
        // we have received our current location, so enable the "Get Current Address" button
    }];
    geocoder=nil;
    _currentLoaction=nil;
 
}
//是否成功获取当前位置
-(BOOL)hasCurrentLocation{
    if(_currentPostionlongitude>0) return YES;
    return NO;
}

-(void)initRightPanelUI{
    CGFloat start_y=0;
    
    CGFloat space_vertical=5; //两个控件垂直之间的距离
    
    UIView* rightPanel=[[UIView alloc] initWithFrame:CGRectMake(left_margin +left_pane_width+2, 0, land_full_width-left_pane_width, land_full_height)];
    rightPanel.layer.borderWidth=1.0;
    rightPanel.backgroundColor=PANEL_BACKGROUND_COLOR;
    [self.view addSubview:rightPanel];
    
    start_y=start_y+top_margin;
    
   _titleView=[[LTTitleView alloc] initWithFrame:CGRectMake(0, start_y, land_full_width-left_pane_width, title_height)];
    _titleView.delegate=self;
    [rightPanel addSubview:_titleView];
    
    start_y=start_y+space_vertical+title_height;
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize=CGSizeMake(160,200);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
     _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(5, start_y, land_full_width-left_pane_width-5, land_full_height - start_y - google_ad_height) collectionViewLayout:flowLayout];
    
    [_collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];
    
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.backgroundColor=[UIColor clearColor];
    
    [rightPanel addSubview:_collectionView];
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(_collectionView.frame.size.width/2 ,_collectionView.frame.size.height/2, 200, 20)];
    _loadMoreTip.textAlignment=NSTextAlignmentLeft;
    _loadMoreTip.text=@"";
    _loadMoreTip.textColor=[UIColor blueColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    _loadMoreTip.hidden=YES;
    [_collectionView addSubview:_loadMoreTip];
    
    start_y=start_y+_collectionView.frame.size.height;
    
    /*
    bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            start_y ,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];    // 指定广告单元ID。
    
    bannerView_.adUnitID = @"a15325556e7d6c3";
  
    bannerView_.rootViewController = self;
    [self.view addSubview:bannerView_];
    GADRequest *request = [GADRequest request];
 
    [bannerView_ loadRequest:request];

    [rightPanel addSubview:bannerView_];
   */
    adBanner = [[MobiSageAdBanner alloc] initWithAdSize:Ad_320X50 withDelegate:self];
    adBanner.frame = CGRectMake(2, start_y+5, 320, 50);
    [adBanner setInterval:Ad_Refresh_30];
    //设置广告轮播动画效果
    [adBanner setSwitchAnimeType:Random];
    [rightPanel addSubview:adBanner];

     //自定义广告
    //start_y=start_y + bannerView_.frame.size.height ;
    advView=[[AdvView alloc] initWithFrame:CGRectMake( adBanner.frame.size.width +30,adBanner.frame.origin.y,450 ,50) aList:nil];
   
    advView.advDelegate=self;

    [rightPanel addSubview:advView];
    
}


- (void)viewDidAppear:(BOOL)animated {
     // 后台线程读取广告
    [NSThread detachNewThreadSelector:@selector(loadAdvInBackground) toTarget:self withObject:nil];
}

/**
 后台线程读取广告
*/
-(void)loadAdvInBackground{
    
    NSMutableArray*  advList=[[NSMutableArray alloc] init];
    if([CommonConfigUtil checkNetworkReachable]){ 

		//晚上增加 app 参数
        

        NSString *url = [[NSString alloc] initWithFormat:@"%@/ad/list/?category=%@&coverId=%@&appID=%@&app=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getAppAdvType],[CommonConfigUtil getCoverId],[CommonConfigUtil getApp]
                         ,[CommonConfigUtil getApp]];
        
      //  NSLog(@"url:%@",url);
        
        NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy: 
                               NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
        
        NSHTTPURLResponse *urlResponse;
        NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
        
 
		
        NSError *error=nil;
        NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];;
        
        if(!error){
            
            [advList removeAllObjects];
            
            NSArray *advArray=[dictionary objectForKey:@"adList"];  
            for(int i=0;nil!=advArray&&i<[advArray count];i++){
                NSMutableDictionary *currentAdv=[[NSMutableDictionary alloc] initWithCapacity:0];  
                //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
                
                
                NSString *advid=[[advArray objectAtIndex:i] objectForKey:@"id"];//广告id
                NSString *advtype=[[advArray objectAtIndex:i] objectForKey:@"type"];
                NSString *name=[[advArray objectAtIndex:i] objectForKey:@"name"];//广告名称
                NSString *photo=[[advArray objectAtIndex:i] objectForKey:@"photo"];//图路径
                NSString *fullPath=[[advArray objectAtIndex:i] objectForKey:@"fullPath"];//图路径
                NSString *objectid=[[advArray objectAtIndex:i] objectForKey:@"objectid"];//内容ID
                NSString *objectName=[[advArray objectAtIndex:i] objectForKey:@"objectName"];//内容名称
                NSString *urlparams=[[advArray objectAtIndex:i] objectForKey:@"urlparams"]; //url附加参数
                NSString *loaclPhotoPath;
                
                if(nil==advtype)advtype=@"";
                if(nil==name)name=@"";
                if(nil==fullPath)fullPath=@"";
                if(nil==objectid)objectid=@"";
                if(nil==objectName)objectName=@"";
                if(nil==advid)advid=@"";
                if(nil==urlparams)urlparams=@"";
                
                if(nil==photo){
                    loaclPhotoPath=[NSString stringWithFormat:@"%@/adv_image_%@.jpg",[CommonConfigUtil getImageLocalPath],advid];
                }
                else{
                    NSString *fileName=[photo stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
                    
                    loaclPhotoPath=[NSString stringWithFormat:@"%@/adv_%@",[CommonConfigUtil getImageLocalPath],fileName];//age图 
                    
                    
                }

		
                [currentAdv setObject:advid forKey:@"advid"];//广告id
                [currentAdv setObject:advtype forKey:@"advtype"];//类型
                [currentAdv setObject:name forKey:@"name"];//类型
                [currentAdv setObject:fullPath forKey:@"image"];
                [currentAdv setObject:objectid forKey:@"objectId"]; 
                [currentAdv setObject:objectName forKey:@"objectName"]; 
                [currentAdv setObject:loaclPhotoPath forKey:@"adv_image_local"];
                [currentAdv setObject:urlparams forKey:@"urlparams"];
                
                [advList addObject:currentAdv];
                
            }  
            
            
            
        } 
        
    }
    
 
   //在主线程种显示广告
    [self performSelectorOnMainThread:@selector(showAdvInMain:) withObject:advList waitUntilDone:NO];
}
-(void)showAdvInMain:(NSMutableArray*)advList{
    [advView resetdAdvList:advList];
}

/**
  用户点击广告图片后的处理
*/
- (void)advSelectWithParams:(NSDictionary *) params{
    NSString *advid=[params objectForKey:@"advid" ];
    NSString *advtype=[params objectForKey:@"advtype" ];
    //  NSString *name=[params objectForKey:@"name" ];
    NSString *objectId=[params objectForKey:@"objectId" ];
    NSString *objectName=[params objectForKey:@"objectName" ];
    NSString *urlparams=[params objectForKey:@"urlparams" ];
    
    
    
    if(nil!=advid && ![@"" isEqualToString:advid]){
        
      //  NSDictionary *statParms =[NSDictionary dictionaryWithObjectsAndKeys:advid,@"objectid",@"ad",@"page",nil];
      //  [NSThread detachNewThreadSelector:@selector(saveMobileStat:) toTarget:self withObject:statParms];
    }
    
    
    NSLog(@"advtype==%@",advtype);
    //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
    
    if([@"0" isEqualToString:advtype] || [advtype intValue]==0 ){
        
        
    }
    else  if([@"1" isEqualToString:advtype] || [advtype intValue]==1 ){
        
    }
    else  if([@"2" isEqualToString:advtype] || [advtype intValue]==2 ){
        
        
        
        
    }
    else  if([@"3" isEqualToString:advtype] || [advtype intValue]==3 ){
        
        
    }
    else  if([@"4" isEqualToString:advtype] || [advtype intValue]==4 ){
        
        
    }
    else  if([@"5" isEqualToString:advtype] || [advtype intValue]==5 ){
        
       
    }else  if([@"8" isEqualToString:advtype] || [advtype intValue]==8 ){
        
        
        NSString *appName=@"";
        if(nil!=urlparams && ![@"" isEqualToString:urlparams] ){
            NSArray *paramsArray=[urlparams componentsSeparatedByString:@"appname="];
            if(nil!=paramsArray &&  [paramsArray count]>1 ){
                appName= [paramsArray objectAtIndex:1 ];
            }
            
        }
        
        if(nil==appName)appName=@"";
        
        if(![@"" isEqualToString:appName] && [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:appName]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appName]];
        }
        else{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
        }
        
    }
    else  if([@"9" isEqualToString:advtype] || [advtype intValue]==9 ){
        
        //start with app:
        if ([objectName hasPrefix:@"app:"]){
            //[self advAppUrlParseWithAppUrl:objectName withUrlparams:urlparams withUINavigationController:navigationController];
        }
        else if(nil!=objectId && ([@"1" isEqualToString:objectId] || [objectId intValue]==1)  ) {
            
            
            [self showWebView:objectName];
            // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
            
        }
        else {
            [self showWebView:objectName];
        }
    }
    

}
-(void) showWebView:(NSString*) url{
    
    JXWWebViewController * buyWebController=[[JXWWebViewController alloc]init];
    buyWebController.webURL=url;
    UINavigationController* navi=[[UINavigationController alloc] initWithRootViewController:buyWebController];
    [self presentViewController:navi animated:YES completion:nil];
    
    buyWebController=nil;
    
    
    
    
}
-(void)viewDidDisappear:(BOOL)animated{
    
}
-(void)dealloc{
    //bannerView_ =nil ;
    adBanner=nil;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(_arrayScenery !=nil) return _arrayScenery.count;
    
    return 0;
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
    if(_arrayScenery !=nil && _arrayScenery.count>indexPath.row){
        NSDictionary* dict=[_arrayScenery objectAtIndex:indexPath.row];
       cell.lblTitle.text=[dict objectForKey:@"sceneryName"];
        cell.lblPrice.text=[NSString stringWithFormat:@"最低价:¥ %@",[dict objectForKey:@"amountAdv"]];
        NSString* imageName=[dict objectForKey:@"imgPath"];
        
        //NSString *fileName=[imageName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
        
        NSString* localImagePath=[NSString stringWithFormat:@"%@/%@",[CommonConfigUtil getImageLocalPath],[imageName stringByReplacingOccurrencesOfString:@"/" withString:@"_"]];
        
        NSString* netImagePath=[NSString stringWithFormat:@"%@160_120/%@",[CommonConfigUtil getTongChenImageBaseUrl],imageName];
        //cell.imageView.image=[UIImage imageNamed:@"loadingImage"];
        
      //  NSDictionary* dictImage=[NSDictionary dictionaryWithObjectsAndKeys:localImagePath,@"localImagePath",netImagePath,@"netImagePath",indexPath,@"indexPath", nil];
        
       // cell.imageView.image=[UIImage imageNamed:@"loadingImage"];

        
        
      if([CommonConfigUtil existImageWithLocalPath:localImagePath]){
            
            cell.imageView.image=[[UIImage alloc] initWithContentsOfFile:localImagePath];
      }
      else if([CommonConfigUtil writeImage:netImagePath toImagePath:localImagePath]){
            
            cell.imageView.image=[[UIImage alloc] initWithContentsOfFile:localImagePath];
            
        }else{
            NSURL* url=[NSURL URLWithString:netImagePath];
            cell.imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        }
        
    }
    return cell;
}
-(void)downloadImageInBackground:(NSDictionary*)dict{
    NSString* netImagePath=[dict objectForKey:@"netImagePath"];
    NSString* localImagePath=[dict objectForKey:@"localImagePath"];
    NSIndexPath *indexPath=[dict objectForKey:@"NSIndexPath"];
    
    if([CommonConfigUtil writeImage:netImagePath toImagePath:localImagePath]){
        
          [self performSelectorOnMainThread:@selector(refreshImage:) withObject:dict waitUntilDone:NO];
        /*
       CollectionCell *cell= (CollectionCell*)[_collectionView cellForItemAtIndexPath:indexPath];
        
        cell.imageView.image=[[UIImage alloc] initWithContentsOfFile:localImagePath];
        [cell.imageView setNeedsDisplay];
        [cell setNeedsDisplay];*/
       
        
    }
}
-(void)refreshImage:(NSDictionary*)dict{

    NSString* netImagePath=[dict objectForKey:@"netImagePath"];
    NSString* localImagePath=[dict objectForKey:@"localImagePath"];
    NSIndexPath *indexPath=[dict objectForKey:@"NSIndexPath"];
    
    
        CollectionCell *cell= (CollectionCell*)[_collectionView cellForItemAtIndexPath:indexPath];
        
        cell.imageView.image=[[UIImage alloc] initWithContentsOfFile:localImagePath];
        [cell.imageView setNeedsDisplay];
        [cell setNeedsDisplay];
    [cell setNeedsLayout];
    
}

-(void)initLeftPanelUI{
    CGFloat start_y=0;
    CGFloat start_x=left_margin;
    CGFloat space_vertical=5; //两个控件垂直之间的距离
    
 
   UIView* leftPanel=[[UIView alloc] initWithFrame:CGRectMake(left_margin, 0, left_pane_width, land_full_height)];
    
 
    leftPanel.backgroundColor=PANEL_BACKGROUND_COLOR;
    [self.view addSubview:leftPanel];
    

    
   
    start_y=start_y+top_margin;
  
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(start_x, start_y, left_pane_width -left_margin, searchField_height)];
   // searchBar.backgroundColor=[UIColor whiteColor];
    searchBar.placeholder=@"输入景点名称搜索";
     searchBar.delegate=self;
    [leftPanel addSubview:searchBar];
    
    
    start_y=start_y  +searchField_height+ space_vertical;
    
    /*
      [self loadLastVisit];
      
      _visitView=[[LTLastVisitView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
      _visitView.delegate=self;
      if(_lastVisitSceneryArray.count>0){
         CGRect visitHistoryFrame=CGRectMake(start_x, start_y, left_pane_width -left_margin,visitTabelView_height);
  	[_visitView resetFrame:visitHistoryFrame];
        _visitView.arrayVisits=_lastVisitSceneryArray;
        start_y=start_y + visitTabelView_height + space_vertical;
    }
    [leftPanel addSubview:_visitView];
  */
    _themeTabelView=[[LTThemeView alloc] initWithFrame:CGRectMake(start_x, start_y, left_pane_width -left_margin, land_full_height - start_y-10 )];
    _themeTabelView.delegate=self;

   
    [leftPanel addSubview:_themeTabelView];
    
    
}
-(void)searchSceneryByNameInBackground:(NSString*)keyWord{
    NSString* xmlData=[LocalTravelRequest searchSceneryByKeyWordInCity:_currentCityID keyWord:keyWord page:1 pageSize:100];
    [self parseData:xmlData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  
    [searchBar resignFirstResponder];   //隐藏输入键盘
    _loadMoreTip.hidden=YES;
    _loadMoreTip.text=@"";
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    [_titleView showActivityIndicator:@"正在加载数据..."];
     [_titleView clearDistance];
    

     _currentPage=1;
      _totalPage=0;//总页数
     _keyWord=searchBar.text;//搜索关键词
     _distance=0;
     _themeId=themeID;

     [self loadData];

  //  [NSThread detachNewThreadSelector:@selector(searchSceneryByNameInBackground:) toTarget:self withObject:searchBar.text];

}
-(void) visitDidSelection:(NSString*) sceneryID sceneryName:(NSString*)sceneryName{
    NSLog(@"%@ %@",sceneryID,sceneryName);
}

-(void)themeSearchInBackground:(NSString*)themeID{
    NSString* xmlData=[LocalTravelRequest getSceneryListByCityIdThemeId:_currentCityID themeId:themeID page:1 pageSize:100];
    [self parseData:xmlData];
}
-(void) themeDidSelection:(NSString*) themeID themeName:(NSString*)themeName{
    _loadMoreTip.hidden=YES;
    _loadMoreTip.text=@"";
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    [_titleView showActivityIndicator:@"正在加载数据..."];
     [_titleView clearDistance];
    


      _currentPage=1;
      _totalPage=0;//总页数
     _keyWord=@"";//搜索关键词
     _distance=0;
     _themeId=themeID;

     [self loadData];

    //[NSThread detachNewThreadSelector:@selector(themeSearchInBackground:) toTarget:self withObject:themeID];
    

    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)distanceSearchInBackground:(NSString*)distance{
    
    NSString* xmlData= [LocalTravelRequest getSceneryListByCityId:_currentCityID page:1 pageSize:100 latitude:[NSString stringWithFormat:@"%f",_currentPostionlatitude] longitude:[NSString stringWithFormat:@"%f",_currentPostionlongitude] radius:distance];
    [self parseData:xmlData ];

}
-(void)distanceSelected:(int )distance{
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    _loadMoreTip.hidden=YES;
    _loadMoreTip.text=@"";
    [_titleView showActivityIndicator:@"正在加载数据..."];


      _currentPage=1;
      _totalPage=0;//总页数
     _keyWord=@"";//搜索关键词
     _distance=distance;
     _themeId=@"";

     [self loadData];
    
   // [NSThread detachNewThreadSelector:@selector(distanceSearchInBackground:) toTarget:self withObject:[NSString stringWithFormat:@"%d",distance]];
 
}
-(void)citySelected:(NSString* )cityID cityName:(NSString*)cityName{
    [_titleView showActivityIndicator:@"正在加载数据..."];
    _currentCityID=cityID;
    _loadMoreTip.hidden=YES;
    _loadMoreTip.text=@"";
    [_titleView clearDistance];

      _currentPage=1;
      _totalPage=0;//总页数
     _keyWord=@"";//搜索关键词
     _distance=0;
     _themeId=@""

     [self loadData];

    //[self searchSceneryByCityID:cityID];
    
     
}

-(void)viewWillAppear:(BOOL)animated{
 
    [_titleView setCurrentCity:_currentCityName];
    [self searchSceneryByCityID:currentCityID];
}
/**
   查找指定城市景点
*/
-(void)searchSceneryByCityName:(NSString*)cityName{
   
    if([cityName hasSuffix:@"市"]) {
        cityName=[cityName substringToIndex:cityName.length -1];
    }
    NSString* cityID=[_appDelegate getCityIDByName:cityName];
    _currentCityID =cityID;
    [self searchSceneryByCityID:cityID];
    
   
    
}

-(void) parseDataByPage:(NSString*)xmlData{
    SceneryListParse* parse=[[SceneryListParse alloc]initWithXmlData:xmlData];
    
    NSMutableDictionary* dictRet=[parse getScenaryList];
    if(dictRet!=nil){
        
      NSString* strTotalPage  =[dictRet objectForKey:@"totalPage"];
        _totalPage=[strTotalPage intValue];
        
       NSMutableArray* newArray=[dictRet objectForKey:@"sceneryArray"];
    
       parse=nil;
       if( _arrayScenery.count==0){
          [_arrayScenery addObjectsFromArray:newArray];
           [_collectionView reloadData];
       }else{
           int count=_arrayScenery.count;
           [_collectionView performBatchUpdates:^{
              [_arrayScenery addObjectsFromArray:newArray];
               
               NSMutableArray* arrayIndexPath=[NSMutableArray array];
               for (int i=0; i<newArray.count; i++) {
                   
                   [arrayIndexPath addObject:[NSIndexPath indexPathForItem:count+i inSection:0]];
               }
              
               [_collectionView insertItemsAtIndexPaths:arrayIndexPath];
               
           } completion:nil];
           
           
       }
    
        
   }

    if(_arrayScenery==nil || _arrayScenery.count==0){
        _loadMoreTip.hidden=NO;
        _loadMoreTip.text=@"未找到景点数据！";
       [_titleView stopActivityIndicator:@""];
    }else{
        
        [_titleView stopActivityIndicator:@""];
        _loadMoreTip.hidden=YES;
        
    }
    
}

-(void) parseData:(NSString*)xmlData{
    SceneryListParse* parse=[[SceneryListParse alloc]initWithXmlData:xmlData];
    
    _arrayScenery=[parse getScenaryList];
    parse=nil;
    [_collectionView reloadData];
    
    if(_arrayScenery==nil || _arrayScenery.count==0){
        _loadMoreTip.hidden=NO;
        _loadMoreTip.text=@"未找到景点数据！";
       [_titleView stopActivityIndicator:@""];
    }else{
        
        [_titleView stopActivityIndicator:@""];
        _loadMoreTip.hidden=YES;
        
    }
}

//将城市的景点保存到本地
-(void) writeCitySceneryToLocal:(NSString*) cityID{
    if(_arrayScenery ==nil || _arrayScenery.count==0) return;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@.json",[CommonConfigUtil getFileLocalPath],cityID ];
    NSError* error=nil;
   NSData* jsonData= [NSJSONSerialization dataWithJSONObject:_arrayScenery options:NSJSONWritingPrettyPrinted error:nil];
    if(!error && jsonData !=nil){
        @try{
            [jsonData writeToFile:localCityJson atomically:YES];
            jsonData=nil;
        }@catch(NSException* ex) {
            
        }
    }
    
    
}
//从本地获取城市景点json
-(void)readCitySceneryFromLocal:(NSString*)cityID{
    NSError* error=nil;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@.json",[CommonConfigUtil getFileLocalPath],cityID ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localCityJson];
    if(jsonData !=nil){
        _arrayScenery=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || _arrayScenery==nil || _arrayScenery.count==0) {
            [self readCitySceneryFromNet:cityID];//从网络获取
        }else{
            [_collectionView reloadData];
            
            _loadMoreTip.hidden=NO;
            [_titleView stopActivityIndicator:@""];
        }
    }

}
-(void) readCitySceneryFromNet:(NSString*)cityID{
    //从网络获取
    NSString* xmlData= [LocalTravelRequest getSceneryListByCityId:cityID page:1 pageSize:100];
    [self parseData:xmlData];
    //NSLog(@"%@",xmlData);
}
-(void)searchSceneryByCityID:(NSString*)cityID{

     
     [NSThread detachNewThreadSelector:@selector(searchSceneryByCityIDInBackgroud:) toTarget:self withObject:cityID];
}

-(void)loadData{
    _currentPage = _currentPage+1;

    if(_totalPage==0 || _currentPage>_totalPage){
       _currentPage=1;
    }


   NSDictionary* dict3=[NSDictionary dictionaryWithObjectsAndKeys:_currentCityID,@"cityID",[NSString stringWithFormat:@"%d",_currentPage],@"page",[NSString stringWithFormat:@"%d",_pageSize],@"pageSize",_keyWord,@"keyWord"
   ,_themeId,@"themeId",_distance;,@"radius",_currentPostionlatitude;,@"latitude",_currentPostionlongitude;,@"longitude",nil];

     [NSThread detachNewThreadSelector:@selector(searchSceneryByPageInBackground:) toTarget:self withObject:dict3];
}
/**
  分页搜索景点
*/
-(void)searchSceneryByPageInBackground:(NSDictionary*)dict{
    
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    NSString* cityID=[dict objectForKey:@"cityID"];
 
    
    NSString* page=[dict objectForKey:@"page"];
    NSString* pageSize=[dict objectForKey:@"pageSize"];
    NSString* keyWord=[dict objectForKey:@"keyWord"];
    NSString* themeId=[dict objectForKey:@"themeId"];
    NSString* radius=[dict objectForKey:@"radius"];
    NSString* longitude=[dict objectForKey:@"longitude"];
    NSString* latitude=[dict objectForKey:@"latitude"];
    
    int intRadius=0;
   if(radius !=nil && ![radius isEqualToString:@""]){
       intRadius=[radius intValue];
   }
       
    NSString* xmlData= [LocalTravelRequest searchScenery:cityID themeId:themeId keyWord:keyWord longitude:longitude latitude:latitude radius:intRadius page:[page intValue] pageSize:[pageSize intValue]];
    [self performSelectorOnMainThread:@selector(parseDataByPage:) withObject:xmlData waitUntilDone:NO];
   
    
    
}

-(void)searchSceneryByCityIDInBackgroud:(NSString*)cityID{
    
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    
    [_titleView showActivityIndicator:@"正在加载数据..."];
    
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@.json",[CommonConfigUtil getFileLocalPath],cityID ];
    if([CommonConfigUtil existFileWithLocalPath:localCityJson]){
        
        
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localCityJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                //从网络获取
                [self readCitySceneryFromNet:cityID];
                
            }else{
                //从本地获取
                [self readCitySceneryFromLocal:cityID];
            }
        }else{
            //从网络获取
            [self readCitySceneryFromNet:cityID];
        }
        
        
        
    }else{
        //从网络获取
        [self readCitySceneryFromNet:cityID];
        
    }
    [self writeCitySceneryToLocal:cityID];
  //[NSThread detachNewThreadSelector:@selector(writeCitySceneryToLocal:) toTarget:self withObject:cityID];
   
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(_arrayScenery ==nil || _arrayScenery.count<indexPath.row) return ;


 
    [self showSceneryDetailInPopover:[_arrayScenery objectAtIndex:indexPath.row]];

   [NSThread detachNewThreadSelector:@selector(saveLastVisitInBackground:) toTarget:self withObject:[_arrayScenery objectAtIndex:indexPath.row]];

   
}

-(void)showSceneryDetailInPopover:(NSDictionary*)dict{
     LTDetailViewController* detailVC=[[LTDetailViewController alloc]init];
    detailVC.dictScenery=dict;
    UINavigationController* navi=[[UINavigationController alloc]initWithRootViewController:detailVC ];
     
     
     _popoverDetail=[[UIPopoverController alloc]initWithContentViewController:navi];
  
    _popoverDetail.contentViewController=navi;
    _popoverDetail.popoverContentSize=CGSizeMake(850, 660);
    
    CGRect frame=_titleView.frame;
    frame.origin.y=frame.origin.y-25;
    
    [_popoverDetail presentPopoverFromRect:frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    detailVC=nil;
    navi=nil;
}

/**
  保存最近访问记录
*/
-(void)saveLastVisitInBackground:(NSDictionary*)dictScenery{
    if(dictScenery ==nil) return ;

    if(_lastVisitSceneryArray==nil){
         _lastVisitSceneryArray=[[NSMutableArray alloc] init];

    }

    if(_lastVisitSceneryArray.count>5){

       [_lastVisitSceneryArray replaceObjectAt:0 withObject:dictScenery];
    }else{
       [_lastVisitSceneryArray addObject:dictScenery];
    }
    
 
   [self writeLastVisitToLocal];


}
/**
  读取最近访问
*/
-(void)loadLastVisit{
    NSString* lastVisitJson=[NSString stringWithFormat:@"%@/lastVisit.json",[CommonConfigUtil getFileLocalPath] ];
    
  if([CommonConfigUtil existFileWithLocalPath:lastVisitJson]){
     
    NSData* jsonData=[NSData dataWithContentsOfFile:lastVisitJson];
    if(jsonData !=nil){
        NSError* error;
         _lastVisitSceneryArray=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        
    }
  }else{
     _lastVisitSceneryArray=[[NSMutableArray alloc] init];
  }

}
/**
  将最近访问写入硬盘
*/
-(void)writeLastVisitToLocal{
    NSString* lastVisitJson=[NSString stringWithFormat:@"%@/lastVisit.json",[CommonConfigUtil getFileLocalPath] ];
    [CommonConfigUtil writeJsonToLocal:_lastVisitSceneryArray localFile:lastVisitJson];
}
-(void) visitDidSelection:(NSDictionary*)dictScenery{

   [self showSceneryDetailInPopover:dictScenery];
}
@end
